package com.sky.aop;

import com.sky.annotation.AutoFill;
import com.sky.constant.AutoFillConstant;
import com.sky.context.BaseContext;
import com.sky.enumeration.OperationType;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.time.LocalDateTime;

@Aspect
@Component
public class AutoAspect {

    @Before("@annotation(com.sky.annotation.AutoFill)")
    public void autoFill(JoinPoint joinPoint) {
        //1.获取当前方法 上的AutoFill 注解，获取枚举项 判断是新增还是修改
        MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
        Method method = methodSignature.getMethod();
        AutoFill autoFill = method.getAnnotation(AutoFill.class);
        OperationType type = autoFill.value();

        Object[] args = joinPoint.getArgs();
        if (args == null || args.length == 0) {
            return;
        }
        Object entity = args[0];

        //2. 新增 增强四个属性
if (type == OperationType.INSERT){
    Class clazz = entity.getClass();
    try {

        Method setCreatTime = clazz.getDeclaredMethod(AutoFillConstant.SET_CREATE_TIME, LocalDateTime.class);
        setCreatTime.invoke(entity, LocalDateTime.now());

        Method setUpdateTime = clazz.getDeclaredMethod(AutoFillConstant.SET_UPDATE_TIME, LocalDateTime.class);
        setUpdateTime.invoke(entity, LocalDateTime.now());

        Method setCreatUser = clazz.getDeclaredMethod(AutoFillConstant.SET_CREATE_USER, Long.class);
        setCreatUser.invoke(entity, BaseContext.getCurrentId());

        Method setUpdateUser = clazz.getDeclaredMethod(AutoFillConstant.SET_UPDATE_USER, Long.class);
        setUpdateUser.invoke(entity, BaseContext.getCurrentId());
    } catch (Exception e) {

        e.printStackTrace();;
    }
}else if(type == OperationType.UPDATE){
    //3.修改 增强两个属性
    try {
        Method setUpdateTime = entity.getClass().getDeclaredMethod(AutoFillConstant.SET_UPDATE_TIME, LocalDateTime.class);
        Method setUpdateUser = entity.getClass().getDeclaredMethod(AutoFillConstant.SET_UPDATE_USER, Long.class);

        //通过反射为对象属性赋值
        setUpdateTime.invoke(entity,LocalDateTime.now());
        setUpdateUser.invoke(entity, BaseContext.getCurrentId());
    } catch (Exception e) {
        e.printStackTrace();
    }
}



    }
}
